package com.mlnx.push.websocket.server.handler;


import com.mlnx.common.utils.MyLog;
import com.mlnx.mptp.ResponseCode;
import com.mlnx.mptp.push.PushPacket;
import com.mlnx.push.websocket.server.session.WebsocketPushNettySession;
import com.mlnx.push.websocket.server.topic.Topic;
import com.mlnx.push.websocket.server.topic.TopicUtils;
import com.mlnx.push.websocket.server.protocol.SubscribeMessage;
import com.mlnx.tp.base.model.DeviceType;

import java.util.List;

import io.netty.channel.ChannelHandlerContext;

public class SubscribeHandle extends BaseSimpleChannelInboundHandler<SubscribeMessage> {

    MyLog log = MyLog.getLog(getClass());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SubscribeMessage msg)
            throws Exception {

        String topic = msg.getTopic();

        ResponseCode responseCode = ResponseCode.ILLEGAL_TOPICE;

        if (topic != null) {
            WebsocketPushNettySession session = (WebsocketPushNettySession) getSessionManager().getSession(ctx.channel());
            List<Topic> topics = TopicUtils.getTopics(topic);

            log.info(String.format("订阅主题:" + topic));
            if (topics != null) {
                session.setTopics(topics);
                if (msg.getPushSerialType() != null){
                    session.setPushSerialType(msg.getPushSerialType());
                }
                responseCode = ResponseCode.SUCESS;
            }
        }

        if (responseCode.equals(ResponseCode.ILLEGAL_TOPICE)) {
            log.error("非法的订阅主题:" + topic);
        }

        PushPacket packet = new PushPacket().subscribeAck(DeviceType.SERVER,
                responseCode);
        ctx.channel().writeAndFlush(packet);
    }

}
